package com.artifex.mupdf.viewer

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.Insets
import androidx.core.view.MenuProvider
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.artifex.mupdf.viewer.databinding.ActivityPatternManagerBinding
import com.artifex.mupdf.viewer.databinding.ItemPatternBinding
import java.nio.charset.StandardCharsets
import java.util.Base64


class PatternManagerActivity : AppCompatActivity(), MenuProvider {

    private lateinit var binding: ActivityPatternManagerBinding
    private lateinit var patternManager: SentencePatternManager
    private lateinit var adapter: PatternAdapter

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        ViewCompat.setOnApplyWindowInsetsListener(
            window.decorView,
            OnApplyWindowInsetsListener { v: View?, insets: WindowInsetsCompat? ->
                val systemBars: Insets = insets!!.getInsets(WindowInsetsCompat.Type.systemBars())
                v!!.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
                insets
            })
        super.onCreate(savedInstanceState)
        if (intent.data == null) return;
        binding = ActivityPatternManagerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val scope = Base64.getUrlEncoder().encodeToString(
            intent.data.toString().toByteArray(
                StandardCharsets.UTF_8
            )
        )
        // Initialize components
        patternManager = SentencePatternManager(this, scope)
        setupToolbar()
        setupRecyclerView()
//        setupAddButton()
        // Register as a MenuProvider with the host activity
//        addMenuProvider(this)
        binding.toolbar.addMenuProvider(this)
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    private fun setupRecyclerView() {
        adapter = PatternAdapter(
            patterns = patternManager.patterns,
            onItemClick = { pattern -> showPatternEditor(pattern) },
            onToggleChanged = { pattern, isChecked ->
                val idx = patternManager.patterns.indexOf(pattern)
                if (patternManager.updatePattern(
                        idx,
                        pattern.copy(isEnabled = isChecked)
                    )
                ) {
                    binding.patternsRecycler.post { adapter.notifyItemChanged(idx) }
                } else
                    Toast.makeText(
                        this@PatternManagerActivity,
                        "Update failed, Please try again!",
                        Toast.LENGTH_LONG
                    ).show()
            },
            onDeleteClick = { pattern ->
                showDeleteConfirmation(pattern)
            }
        )

        binding.patternsRecycler.apply {
            layoutManager = LinearLayoutManager(this@PatternManagerActivity)
            adapter = this@PatternManagerActivity.adapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }
    }

//    private fun setupAddButton() {
//        binding.addPatternButton.setOnClickListener {
//            showPatternEditor(null)
//        }
//    }

    private fun showPatternEditor(pattern: SentencePattern?) {
        PatternEditorDialog(pattern) { newPattern ->
            if (pattern == null) {
                val idx = patternManager.patterns.size;
                patternManager.addPattern(newPattern)
                binding.patternsRecycler.post { adapter.notifyItemInserted(idx) }
            } else {
                val index = patternManager.patterns.indexOf(pattern)
                patternManager.updatePattern(index, newPattern)
                binding.patternsRecycler.post { adapter.notifyItemChanged(index) }
            }
//            refreshPatterns()
        }.show(supportFragmentManager, "pattern_editor")
    }

    private fun showDeleteConfirmation(pattern: SentencePattern) {
        AlertDialog.Builder(this)
            .setTitle("Delete Pattern")
            .setMessage("Are you sure you want to delete '${pattern.name}'?")
            .setPositiveButton("Delete") { _, _ ->
                val index = patternManager.patterns.indexOf(pattern)
                patternManager.removePattern(index)
//                refreshPatterns()
                binding.patternsRecycler.post { adapter.notifyItemRemoved(index) }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.pattern_menu, menu)
    }

    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return when (menuItem.itemId) {
            R.id.action_add -> {
                showPatternEditor(null)
                true // Consume the event
            }

            // You can handle other menu items here if needed
            else -> false // Let the activity or other fragments handle the event
        }
    }

//    private fun refreshPatterns() {
//        adapter.updatePatterns(patternManager.patterns)
//    }

    inner class PatternAdapter(
        private var patterns: List<SentencePattern>,
        private val onItemClick: (SentencePattern) -> Unit,
        private val onToggleChanged: (SentencePattern, Boolean) -> Unit,
        private val onDeleteClick: (SentencePattern) -> Unit
    ) : RecyclerView.Adapter<PatternAdapter.PatternViewHolder>() {

        inner class PatternViewHolder(val binding: ItemPatternBinding) :
            RecyclerView.ViewHolder(binding.root)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PatternViewHolder {
            val binding = ItemPatternBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
            return PatternViewHolder(binding)
        }

        override fun onBindViewHolder(holder: PatternViewHolder, position: Int) {
            val pattern = patterns[position]
            holder.binding.apply {
                patternName.text = pattern.name
                patternRegex.text = pattern.regex
                enabledSwitch.isChecked = pattern.isEnabled

                root.setOnClickListener { onItemClick(pattern) }
                enabledSwitch.setOnCheckedChangeListener { _, isChecked ->
                    onToggleChanged(pattern, isChecked)
                }
                deleteButton.setOnClickListener { onDeleteClick(pattern) }
            }
        }

        override fun getItemCount() = patterns.size

//        fun updatePatterns(newPatterns: List<SentencePattern>) {
//            patterns = newPatterns
//        }
    }
}